from django.db import models
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager


# 用户Manager类
class CustomUserManager(BaseUserManager):
    use_in_migrations = True  # 使得manager在迁移时可用

    def get_by_natural_key(self, username):
        return self.get(username=username)


# 用户表
class User(AbstractBaseUser):
    user_id = models.AutoField(primary_key=True, verbose_name='id')
    username = models.CharField(max_length=32, unique=True, verbose_name='用户账号')
    password = models.CharField(max_length=255, verbose_name='用户密码')
    email = models.EmailField(unique=True, verbose_name='用户邮箱')
    nickname = models.CharField(max_length=32, null=True, blank=True, verbose_name='用户昵称')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    last_login = models.DateTimeField(auto_now=True, verbose_name='最后登录时间')

    objects = CustomUserManager()
    USERNAME_FIELD = 'username'

    def __str__(self):
        return f"{self.user_id}: {self.username}"

    def set_password(self, raw_password):
        self.password = make_password(raw_password)
        self.save(update_fields=['password'])

    def check_password(self, raw_password):
        return check_password(raw_password, self.password)


# 文章表
class Article(models.Model):
    article_id = models.AutoField(primary_key=True, verbose_name='文章id')
    author_id = models.IntegerField(verbose_name='作者id')
    title = models.CharField(max_length=64, verbose_name='标题')
    content = models.TextField(verbose_name='正文')

    def __str__(self):
        return self.title


# 标签表
class Tag(models.Model):
    tag_id = models.AutoField(primary_key=True, verbose_name='标签id')
    name = models.CharField(max_length=32, verbose_name='标签名称')

    def __str__(self):
        return self.name


# 文章标签表
class ArticleTag(models.Model):
    tag_id = models.IntegerField(verbose_name='标签id')
    article_id = models.IntegerField(verbose_name='文章id')

    def __str__(self):
        return f"tag_id: {self.tag_id}, article_id: {self.article_id}"


# 评论表
class Comment(models.Model):
    comment_id = models.AutoField(primary_key=True, verbose_name='评论id')
    content = models.TextField()
    author_id = models.IntegerField(verbose_name="用户id")
    article_id = models.IntegerField(verbose_name="文章id")
    parent_comment_id = models.IntegerField(verbose_name="父评论id", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='评论时间')

    def __str__(self):
        return f"article_id: {self.article_id}, content: {self.content}"
